package com.cloudshop.service.common.config.feign;

import com.cloudshop.service.common.enums.RequestEnum;
import feign.RequestInterceptor;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign 配置类.
 *
 * @author 宫新程
 * @since 2019/3/29 19:14
 */
@Slf4j
@Configuration
public class FeignConfigBean {

  @Value("${spring.application.name}")
  private String projectName;

  /** Feign调用时，传递Header. */
  @Bean
  public RequestInterceptor requestInterceptor() {
    return requestTemplate -> {
      String requestId = getRequestId();
      String token = getToken();
      requestTemplate.header(RequestEnum.REQUEST_ID.getCode(), requestId);
      requestTemplate.header(RequestEnum.TOKEN.getCode(), token);
      requestTemplate.header(RequestEnum.FROM_SYSTEM.getCode(), projectName);
    };
  }

  /** 获取令牌token. */
  private String getToken() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    ServletRequestAttributes servletRequestAttributes =
        (ServletRequestAttributes) requestAttributes;
    HttpServletRequest request = servletRequestAttributes.getRequest();
    String token = request.getHeader(RequestEnum.TOKEN.getCode());
    log.info("Feign 调用获取 Authorization：{}", token);
    return token;
  }

  /**
   * 获取请求中的 requestId.
   *
   * @return Header
   */
  private String getRequestId() {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    ServletRequestAttributes servletRequestAttributes =
        (ServletRequestAttributes) requestAttributes;
    HttpServletRequest request = servletRequestAttributes.getRequest();
    String requestId = (String) request.getAttribute(RequestEnum.REQUEST_ID.getCode());
    log.info("Feign 调用获取 request-id：{}", requestId);
    return requestId;
  }
}
